// EventBus.ts
import mitt, { Emitter, Handler } from "mitt";

const eventNames = ["chat:readed:message", "chat:active:user"] as const;

type EventNames = (typeof eventNames)[number];

const mitter = mitt();

export function emit(eventName: EventNames, args: any) {
  mitter.emit(eventName, args);
}

export function on<T>(eventName: EventNames, listener: Handler) {
  mitter.on(eventName, listener);
}

export function allDelete(eventName: EventNames) {
  mitter.all.delete(eventName);
}

// export interface EventBus<EventTypes extends Record<string, any>> extends Emitter<EventTypes> {}

// function createEventBus<EventTypes extends Record<string, any>>(): EventBus<EventTypes> {
//   return mitt<EventTypes>();
// }

// function on<EventTypes extends Record<string, any>>(bus: EventBus<EventTypes>, event: keyof EventTypes, listener: Handler<EventTypes[keyof EventTypes]>): void {
//   bus.on(event as string, listener);
// }

// function off<EventTypes extends Record<string, any>>(bus: EventBus<EventTypes>, event: keyof EventTypes, listener: Handler<EventTypes[keyof EventTypes]>): void {
//   bus.off(event as string, listener);
// }

// function emit<EventTypes extends Record<string, any>>(bus: EventBus<EventTypes>, event: keyof EventTypes, payload?: EventTypes[keyof EventTypes]): void {
//   bus.emit(event as string, payload);
// }

// export function useEventBus<EventTypes>(): { on: <K extends keyof EventTypes>(event: K, listener: Handler<EventTypes[K]>) => void, off: <K extends keyof EventTypes>(event: K, listener: Handler<EventTypes[K]>) => void, emit: <K extends keyof EventTypes>(event: K, payload?: EventTypes[K]) => void } {
//   const eventBus = createEventBus<EventTypes>();

//   return {
//     on: <K extends keyof EventTypes>(event: K, listener: Handler<EventTypes[K]>) => {
//       on(eventBus, event, listener);
//     },
//     off: <K extends keyof EventTypes>(event: K, listener: Handler<EventTypes[K]>) => {
//       off(eventBus, event, listener);
//     },
//     emit: <K extends keyof EventTypes>(event: K, payload?: EventTypes[K]) => {
//       emit(eventBus, event, payload);
//     },
//   };
// }
